package com.yinhai.activity;

import java.util.Timer;
import java.util.TimerTask;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.PowerManager;
import android.os.SystemClock;
import android.os.Vibrator;
import android.text.InputType;
import android.text.Selection;
import android.text.Spannable;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.view.View.OnTouchListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.Chronometer;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.ToggleButton;

import com.cmcc.groupcontacts.MainApp;
import com.listener.AccountConflictMonitor.onAccountConflictListener;
import com.listener.HomeReceiver;
import com.listener.TelListener;
import com.littlec.sdk.utils.MyLogger;
import com.yinhai.model.VOIPPhoneRecord;
import com.yinhai.util.CommonUtils;
import com.yinhai.util.Constants;
import com.yinhai.util.NotificationController;
import com.yinhai.view.DialogFactory;

/**
 * 单呼呼叫/来电界面
 */
public class CallActivity extends Activity implements OnClickListener, TelListener {
    private static final MyLogger sLogger = MyLogger.getLogger("CallActivity");
    
    
    
    private static final int MSG_DOT_CHANGE = 1000;
    
    private static final int TIMER_DELAY = 0;
    
    private static final int TIMER_PRIOD = 300;
    
    /** 当前已处在挂断状态了，正在执行，按挂断按钮不在重复处理 */
    private boolean mIsHangUp = false;
    
    /** 是否双方已处在通话中 */
    private boolean mIsStart = false;
    
    private boolean mPickUp;
    
    // private boolean mIsPickUp = false;
    private int mDotCount = 0;
    
    private boolean mCallFailed = false;
    
    private boolean fromInComingCall = false;
    
    /** 未成功通话的状态 */
    private int record_status = -1;
    
    /** 拨打及来电电话号码 */
    // private String mPhoneNumber="";
    /** 呼叫时嘟嘟的声音是否在播放 */
    private boolean mIsPlaying = false;
    
    private int mInputType;
    
    /** 拨号盘区域 */
    private LinearLayout mKeyBoardLayout;
    
    /** 静音、免提、拨号盘按钮区域 */
    // private LinearLayout mMenuBarLayout;
    /** 数字拨号盘、 静音、免提、拨号盘按钮区域 */
    private View mMenuView;
    
    /** 挂断按钮区域 */
    private LinearLayout mHangup;
    
    /** 底部接听与拒绝的布局 */
    private RelativeLayout mPickupRefuseLayout;
    
    /** 显示联系人姓名 */
    private TextView mContactNameTextView;
    
    /** 显示电话号码 */
    private TextView mTelnumTextView;
    
    /** 通话时长计时器 */
    private Chronometer mChronometer;
    
    /** 拨号时的三个点动画 */
    private TextView mDotTextView;
    
    /** 删除数字号码按钮 */
    private ImageButton mDeleteNumImageButton;
    
    /** 拨号盘中用来显示及编辑的电话号码区域 */
    private EditText mPhoneNumberEditText;
    
    /** 静音按钮 */
    private ToggleButton mMuteToggleButton;
    
    /** 免提按钮 */
    private ToggleButton mHFToggleButton;
    
    /** 拨号盘按钮 */
    private ToggleButton mKeyBoardToggleButton;
    
    /** 来电接听按钮 */
    private Button mPickUpButton;
    
    /** 来电拒绝按钮 */
    private Button mRefuseButton;
    
    /** 呼叫时播放三声嘟嘟的声音的播放器 */
    private MediaPlayer mMediaPlayer;
    
    /** 来电铃声播放器 */
    private MediaPlayer mInComingPlayer = null;
    
    /** 语音提示播放器 */
    private MediaPlayer mTiPlayer = null;
    
    private AudioManager mAudioManager;
    
    private Vibrator mVibrator;
    
    private PowerManager.WakeLock mWakeLock = null;
    
    /** 通话记录 */
    private VOIPPhoneRecord mPhoneRecord = new VOIPPhoneRecord();
    
    /** 呼叫时三个点动画辅助timer */
    private Timer mTimer = new Timer();
    
    private IntentFilter filterHome = new IntentFilter();
    
    /** 监听按主页键的广播的receiver */
    private HomeReceiver homeReceiver = new HomeReceiver();
    
    private VOIPBroadcastReceiver voipBroadcastReceiver = new VOIPBroadcastReceiver();
    
    
    
    /** 监听通话过程中账号冲突回调 */
    private onAccountConflictListener accountConflictListener = new onAccountConflictListener() {
        
        @Override
        public void onAccountConflict() {
            hangup();
        }
    };
    
    Handler dialHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_DOT_CHANGE: {
                    mDotCount = mDotCount % 3;
                    switch (mDotCount) {
                        case 0:
                            mDotTextView.setText(getString(R.string.onedot));
                            break;
                        case 1:
                            mDotTextView.setText(getString(R.string.twodots));
                            break;
                        case 2:
                            mDotTextView.setText(getString(R.string.threedots));
                            break;
                    }
                    mDotCount++;
                }
            }
            super.handleMessage(msg);
        }
        
    };
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_single_call);
        setWindowFlags();
        registerReceiver();
        initView();
        initListener();
        initData();
        scheduleTimer();
        if (!mPickUp) { // 拨打
            callNumber();
        }
    }
    
    private void setWindowFlags() {
        /** 屏幕常亮、锁屏时来电则屏幕最上 */
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED
            | WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON
            | WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN
            | WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
    }
    
    private void registerReceiver() {
        filterHome.addAction(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);// 主页键广播
        filterHome.addAction(NotificationController.PHONE_NOTIFICATION_ACTION);// 点击消息的广播
        registerReceiver(homeReceiver, filterHome);
        IntentFilter filter = new IntentFilter();
        filter.addAction(Constants.VOIP_CALLSTATECALL_CALLALERTING);
        filter.addAction(Constants.VOIP_CALLSTATECALL_CALLANSWERED);
        filter.addAction(Constants.VOIP_CALLSTATECALL_CALLRELEASED);
        filter.addAction(Constants.VOIP_CALLSTATECALL_MAKECALLFAILED);
        registerReceiver(voipBroadcastReceiver, filter);
    }
    
    private void initView() {
        mMenuView = findViewById(R.id.ll_talking);
        mHangup = (LinearLayout)findViewById(R.id.finish_exit_btn);
        mContactNameTextView = (TextView)findViewById(R.id.contact_name);
        mTelnumTextView = (TextView)findViewById(R.id.telnum_tv_call);
        mChronometer = (Chronometer)findViewById(R.id.state_tv_call);
        mPickUpButton = (Button)findViewById(R.id.pickup_btn);
        mRefuseButton = (Button)findViewById(R.id.refuse_btn);// 被叫时拒绝
        mPickupRefuseLayout = (RelativeLayout)findViewById(R.id.called_lly);// 被叫时接听
        mMuteToggleButton = (ToggleButton)findViewById(R.id.mute_btn);
        mHFToggleButton = (ToggleButton)findViewById(R.id.speaker_btn);
        // mMenuBarLayout = (LinearLayout) findViewById(R.id.dialbar_lly);
        mKeyBoardToggleButton = (ToggleButton)findViewById(R.id.btn_keyboard);
        mDotTextView = (TextView)findViewById(R.id.dot_tv);
        mKeyBoardLayout = (LinearLayout)findViewById(R.id.dial_plate_lly);
        mDeleteNumImageButton = (ImageButton)findViewById(R.id.deleteNum);
        mPhoneNumberEditText = (EditText)findViewById(R.id.dialNumber);
    }
    
    private void initListener() {
        findViewById(R.id.one).setOnClickListener(this);
        findViewById(R.id.two).setOnClickListener(this);
        findViewById(R.id.three).setOnClickListener(this);
        findViewById(R.id.four).setOnClickListener(this);
        findViewById(R.id.five).setOnClickListener(this);
        findViewById(R.id.six).setOnClickListener(this);
        findViewById(R.id.seven).setOnClickListener(this);
        findViewById(R.id.eight).setOnClickListener(this);
        findViewById(R.id.nine).setOnClickListener(this);
        findViewById(R.id.star).setOnClickListener(this);
        findViewById(R.id.zero).setOnClickListener(this);
        findViewById(R.id.pound).setOnClickListener(this);
        mDeleteNumImageButton.setOnClickListener(this);
        mDeleteNumImageButton.setOnLongClickListener(new OnLongClickListener() {
            @Override
            public boolean onLongClick(View arg0) {
                mPhoneNumberEditText.setText("");
                return false;
            }
        });
        mInputType = mPhoneNumberEditText.getInputType();
        mPhoneNumberEditText.setInputType(InputType.TYPE_NULL);
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
            mPhoneNumberEditText.setOnTouchListener(new OnTouchListener() {
                @TargetApi(14)
                @Override
                public boolean onTouch(View v, MotionEvent event) {
                    mPhoneNumberEditText.setInputType(mInputType);
                    if (mPhoneNumberEditText.length() != 0) {
                        mPhoneNumberEditText.setCursorVisible(true);
                        final float x = event.getX();
                        final float y = event.getY();
                        int offset = mPhoneNumberEditText.getOffsetForPosition(x, y);
                        Selection.setSelection((Spannable)mPhoneNumberEditText.getText(), offset);
                    }
                    return true;
                }
            });
        }
        
        // VoIpManager.getInstance().addNetChangeCallBack(mNetChangeCallBack);
        MainApp.instance.getAccountConflictMonitor().addAccountConflictListener(accountConflictListener);
        // VoIpManager.getInstance().addCallStateListener(mVoIpCallStateCallBack);
        // if(mPickUp) {
        mRefuseButton.setOnClickListener(this);
        mPickUpButton.setOnClickListener(this);
        // }
        mHangup.setOnClickListener(this);
        mMuteToggleButton.setOnClickListener(this);
        mHFToggleButton.setOnClickListener(this);
        mKeyBoardToggleButton.setOnClickListener(this);
        // 监听手机自身电话状态
        // PhoneUtils.setTelListener(this);
    }
    
    private void initData() {
        Intent intent = getIntent();
        mPhoneRecord = (VOIPPhoneRecord)intent.getSerializableExtra("data");
        fromInComingCall = intent.getBooleanExtra("fromInComingCall", false);
        mPickUp = intent.getBooleanExtra("pickup", false);// true　被叫 　　false 呼出
        // PhoneUtils.isflush = true;
        mAudioManager = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
        mVibrator = (Vibrator)getSystemService(Service.VIBRATOR_SERVICE);
        if (mPickUp) {// 来电
            mChronometer.setText(R.string.incomingcall);
            mPickupRefuseLayout.setVisibility(View.VISIBLE);
            mMenuView.setVisibility(View.GONE);
            // 来电声音外放且音量键是默认控制通话音量
            setVolumeControlStream(AudioManager.STREAM_VOICE_CALL);
            mAudioManager.setSpeakerphoneOn(true);
            ringstone();
        } else {// 拨打电话
            mChronometer.setText(R.string.calling);
            // 拨打默认听筒且音量键是控制通话音量
            setVolumeControlStream(AudioManager.STREAM_VOICE_CALL);
            mAudioManager.setMode(AudioManager.MODE_IN_COMMUNICATION);
            mAudioManager.setSpeakerphoneOn(false);
            mHFToggleButton.setChecked(false);
            createRingingMusic();
        }
        mTelnumTextView.setText(mPhoneRecord.getTelnum());
        if (!TextUtils.isEmpty(mPhoneRecord.getContactname())) {
            mContactNameTextView.setVisibility(View.VISIBLE);
            mContactNameTextView.setText(mPhoneRecord.getContactname());
        }
    }
    
    private void scheduleTimer() {
        mTimer.schedule(new TimerTask() { // 三个点动画
            @Override
            public void run() {
                dialHandler.sendEmptyMessage(MSG_DOT_CHANGE);
            }
        },
            TIMER_DELAY,
            TIMER_PRIOD);
    }
    
    /** 呼叫 */
    private void callNumber() {
    }
    
    @SuppressLint("Wakelock")
    @Override
    protected void onResume() {
        super.onResume();
        PowerManager pm = (PowerManager)getSystemService(Context.POWER_SERVICE);
        mWakeLock = pm.newWakeLock(PowerManager.ACQUIRE_CAUSES_WAKEUP | PowerManager.SCREEN_BRIGHT_WAKE_LOCK, "TAG");
        mWakeLock.acquire();
    }
    
    @Override
    protected void onStop() {
        super.onStop();
        if (mWakeLock != null) {
            mWakeLock.release();
        }
    }
    
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.pickup_btn: // 接听
                vibrateRingCancel();
                // 默认听筒
                setVolumeControlStream(AudioManager.STREAM_VOICE_CALL);
                mAudioManager.setMode(AudioManager.MODE_IN_COMMUNICATION);
                mAudioManager.setSpeakerphoneOn(false);
                mHFToggleButton.setChecked(false);
                mPickUpButton.setOnClickListener(null);
                mPickUpButton.setEnabled(false);
                mPickupRefuseLayout.setVisibility(View.GONE);
                mMenuView.setVisibility(View.VISIBLE);
                mPhoneRecord.setState(2);
                break;
            case R.id.refuse_btn: // 拒接手动挂断
                mRefuseButton.setOnClickListener(null);
                mRefuseButton.setEnabled(false);
                mPhoneRecord.setState(3);
                mPhoneRecord.setLastTime(0);
                vibrateRingCancel();
            case R.id.finish_exit_btn: // 手动挂断
                if (!mIsStart)
                    record_status = 25;
                /** 主动呼叫后未通话主动取消通话 */
                hangup();
                break;
            case R.id.mute_btn: { // 静音开关
                break;
            }
            case R.id.speaker_btn: { // 免提开关
                mAudioManager.setMode(AudioManager.MODE_IN_COMMUNICATION);
                mAudioManager.setSpeakerphoneOn(mHFToggleButton.isChecked());
                break;
            }
            case R.id.btn_keyboard: { // 数字拨号盘显示/隐藏
                if (mKeyBoardToggleButton.isChecked())
                    mKeyBoardLayout.setVisibility(View.VISIBLE);
                else
                    mKeyBoardLayout.setVisibility(View.INVISIBLE);
                
                break;
            }
            case R.id.one: {
                keyPressed(KeyEvent.KEYCODE_1);
                break;
            }
            case R.id.two: {
                keyPressed(KeyEvent.KEYCODE_2);
                break;
            }
            case R.id.three: {
                keyPressed(KeyEvent.KEYCODE_3);
                break;
            }
            case R.id.four: {
                keyPressed(KeyEvent.KEYCODE_4);
                break;
            }
            case R.id.five: {
                keyPressed(KeyEvent.KEYCODE_5);
                break;
            }
            case R.id.six: {
                keyPressed(KeyEvent.KEYCODE_6);
                break;
            }
            case R.id.seven: {
                keyPressed(KeyEvent.KEYCODE_7);
                break;
            }
            case R.id.eight: {
                keyPressed(KeyEvent.KEYCODE_8);
                break;
            }
            case R.id.nine: {
                keyPressed(KeyEvent.KEYCODE_9);
                break;
            }
            case R.id.star: {
                keyPressed(KeyEvent.KEYCODE_STAR);
                break;
            }
            case R.id.zero: {
                keyPressed(KeyEvent.KEYCODE_0);
                break;
            }
            case R.id.pound: {
                keyPressed(KeyEvent.KEYCODE_POUND);
                break;
            }
            case R.id.deleteNum: {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH
                    && mPhoneNumberEditText.getInputType() == InputType.TYPE_NULL) {
                    mPhoneNumberEditText.setInputType(mInputType);
                    mPhoneNumberEditText.setSelection(mPhoneNumberEditText.length());
                }
                keyPressed(KeyEvent.KEYCODE_DEL);
                if (mPhoneNumberEditText.length() == 0) {
                    mPhoneNumberEditText.setCursorVisible(false);
                }
                
                break;
            }
            
        }
    }
    
    /**
     * 断网引起挂断
     */
    private void hangupByNetwork() {
        if (mIsHangUp)
            return; // 声音播放完执行挂断，
        mIsHangUp = true;
        sLogger.e("hangupByNetwork");
        close();
    }
    
    /**
     * 挂断
     */
    private void hangup() {
        if (mIsHangUp)
            return; // 声音播放完执行挂断，
        mIsHangUp = true;
        
        sLogger.e("hangup");
        close();
    }
    
    /**
     * 底层挂断
     */
    private void hangupByPending() {
        if (mIsHangUp)
            return; // 声音播放完执行挂断，
        mIsHangUp = true;
        sLogger.e("hangupByPending");
        close();
    }
    
    private void close() {
        stopRingingMusic();
        vibrateRingCancel();
        if (mTiPlayer != null) { // 未播放完成,停止播放
            try {
                if (mTiPlayer.isPlaying()) { // java代码与底层c++代码状态不一致
                    mTiPlayer.stop();
                    mTiPlayer.release();
                    mTiPlayer = null;
                }
            } catch (Exception e) {
                mTiPlayer = null;
            }
            
        }
        mHangup.setOnClickListener(null);
        if (mIsStart) {
            String timeShow = mChronometer.getText().toString().trim();
            if (timeShow.equals("通话结束")) {
                return;
            }
            char[] times = timeShow.toCharArray();
            if (times.length == 5 || times.length == 4) {
                mPhoneRecord.setLastTime(parse(times));
            } else {
                mPhoneRecord.setLastTime(0);
            }
        } else {
            mPhoneRecord.setLastTime(0);
        }
        
        mChronometer.stop(); // 停止记数
        mChronometer.setText(R.string.callend);
        mDotTextView.setVisibility(View.GONE);
        saveMessagePhoneRecord();
        // PhoneDAOUtils.getInstance().insertDb_callrecord(mPhoneRecord);
        callFinished();
    }
    
    private void callFinished() {
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                CallActivity.super.finish();
            }
        }, 600);
    }
    
    private int parse(char[] times) {
        int sum = 0;
        if (times.length == 5) { // 00:20
            sum += (times[0] - '0') * 10 * 60 + (times[1] - '0') * 60 + (times[3] - '0') * 10 + (times[4] - '0');
        } else if (times.length == 4) {// 0:20
            sum += (times[0] - '0') * 60 + (times[2] - '0') * 10 + (times[3] - '0');
        }
        return sum;
    }
    
    private void keyPressed(int keyCode) {
        KeyEvent event = new KeyEvent(KeyEvent.ACTION_DOWN, keyCode);
        mPhoneNumberEditText.onKeyDown(keyCode, event);
        if ((keyCode >= KeyEvent.KEYCODE_0 && keyCode <= KeyEvent.KEYCODE_9) || keyCode == KeyEvent.KEYCODE_STAR
            || keyCode == KeyEvent.KEYCODE_POUND) {
            int result_code = CommonUtils.converToAscii(keyCode);
        }
    }
    
    @Override
    protected void onDestroy() {
        unregisterReceiver(homeReceiver);
        unregisterReceiver(voipBroadcastReceiver);
        NotificationController.getInstance().cancelPhoneNotification(); // 若通话结束后状态提示还有则清除
        MainApp.instance.getAccountConflictMonitor().removeAccountConflictListener(accountConflictListener);
        
        if (mTimer != null)
            mTimer.cancel();
        mTimer = null;
        mVibrator = null;
        mAudioManager.setMicrophoneMute(false);
        mAudioManager.setSpeakerphoneOn(false);
        mAudioManager.setMode(AudioManager.MODE_NORMAL);
        super.onDestroy();
    }
    
    private void createRingingMusic() {
        mMediaPlayer = MediaPlayer.create(this, R.raw.default_ringtone);
        if (mMediaPlayer != null) {
            mMediaPlayer.setLooping(true);
        }
    }
    
    private void startRingingMusic() {
        if (mMediaPlayer != null) {
            mMediaPlayer.start();
            mIsPlaying = true;
        }
    }
    
    private void stopRingingMusic() {
        if (mMediaPlayer != null) {
            mMediaPlayer.stop();
            mMediaPlayer.release();
            mMediaPlayer = null;
            mIsPlaying = false;
        }
    }
    
    @Override
    public void finish() {
        DialogFactory.getConfirmDialog2(this,
            getString(R.string.info),
            getString(R.string.iscalldown),
            getString(R.string.cancel),
            getString(R.string.ok),
            null,
            new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    vibrateRingCancel();
                    hangup();// 返回键手动挂断
                }
            }).show();
    }
    
    @SuppressWarnings("deprecation")
    private void ringstone() {
        AudioManager audio = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
        int mode = audio.getRingerMode();
        int isvib = audio.getVibrateSetting(AudioManager.VIBRATE_TYPE_RINGER);
        switch (mode) {
            case AudioManager.RINGER_MODE_SILENT:
                if (isvib == AudioManager.VIBRATE_SETTING_ONLY_SILENT) {// 震动
                    vibrateStart();
                }
                break;
            case AudioManager.RINGER_MODE_VIBRATE:
                vibrateStart(); // 震动
                break;
            case AudioManager.RINGER_MODE_NORMAL:
                if (isvib == AudioManager.VIBRATE_SETTING_ON) { // 铃声和震动
                    vibrateStart();
                }
                playInComingRingtone();
                break;
            default:
                break;
        }
    }
    
    /**
     * 震动
     */
    private void vibrateStart() {
        if (mVibrator.hasVibrator()) {
            mVibrator.vibrate(new long[] {300, 500}, 0);
        }
    }
    
    /**
     * 关闭来电铃声和振动
     */
    private void vibrateRingCancel() {
        stopInComingRingtone();
        if (mVibrator != null)
            mVibrator.cancel();
    }
    
    /**
     * 播放来电铃声
     */
    private void playInComingRingtone() {
        Uri uri = RingtoneManager.getActualDefaultRingtoneUri(this, RingtoneManager.TYPE_RINGTONE);
        mInComingPlayer = new MediaPlayer();
        // 音量键控制铃声音量
        setVolumeControlStream(AudioManager.STREAM_RING);
        mInComingPlayer.setAudioStreamType(AudioManager.STREAM_RING);
        mAudioManager.setStreamVolume(AudioManager.STREAM_RING,
            mAudioManager.getStreamMaxVolume(AudioManager.STREAM_RING),
            0);
        mInComingPlayer.setLooping(true);
        try {
            mInComingPlayer.setDataSource(this, uri);
            mInComingPlayer.prepare();
            mInComingPlayer.start();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    /**
     * 停止播放来电铃声
     */
    private void stopInComingRingtone() {
        try {
            if (mInComingPlayer != null) {
                mInComingPlayer.stop();
                mInComingPlayer.release();
                mInComingPlayer = null;
            }
        } catch (Exception e) {
            e.printStackTrace();
            mInComingPlayer = null;
        }
        
    }
    
    @Override
    public void pickup() {
        // 来电，未接，未挂，未结束
        if (mPhoneRecord.getState() == 0) {
            // 拒接
            mPhoneRecord.setState(3);
            mPhoneRecord.setLastTime(0);
            vibrateRingCancel();
        } else {
        }
        hangup();// IP通话中终端来电手动挂断
    }
    
    @Override
    public void refuseTel() {
        
    }
    
    private void getCallerStatus(int status) {
        record_status = status;
        sLogger.w("对方状态" + status + "#################");
        playMusic(status);
    }
    
    private void playMusic(int status) {
        sLogger.e("to play music ：" + status);
        switch (status) {
            case 0: // 底层已正常挂断 //主呼通后，在被叫接听前主动挂断,则被叫直接挂断
                hangupByPending();
                break;
            case 2:
                break;
            case 4: // LinphoneReasonNotFound: //空号
                break;
            case 20: // LinphoneReasonUnknown:
                break;
            case 5: // LinphoneReasonNotAnswered://A呼B，B来电不接，A超时
                if (!fromInComingCall)// 收到来电后，对方又挂断了
                {
                } else {
                    hangupByPending();
                }
                break;
            case 6: // LinphoneReasonBusy:
                break;
            default:
                break;
        }
    }
    
    
    
    private void createTipMediaPlayer(int sound) {
        
        try {
            mTiPlayer = MediaPlayer.create(this, sound);
            setVolumeControlStream(AudioManager.STREAM_VOICE_CALL);
            mAudioManager.setMode(AudioManager.MODE_IN_COMMUNICATION);// 听筒播放
            mAudioManager.setStreamVolume(AudioManager.STREAM_VOICE_CALL,
                mAudioManager.getStreamMaxVolume(AudioManager.STREAM_VOICE_CALL),
                0);
            mAudioManager.setSpeakerphoneOn(mHFToggleButton.isChecked());
            mTiPlayer.setOnCompletionListener(new OnCompletionListener() {
                @Override
                public void onCompletion(MediaPlayer mp) {
                    if (mp != null)
                        mp.release();
                    mp = null;
                    hangupByPending();
                }
            });
            mTiPlayer.start();
        } catch (Exception e) {
            e.printStackTrace();
        }
        
    }
    
    /**
     * 将通话情况保存到会话界面
     */
    private void saveMessagePhoneRecord() {
        // MsgUtil.doSavePhoneRecordToConversation(mPhoneRecord, record_status);
    }
    
    public class VOIPBroadcastReceiver extends BroadcastReceiver {
        
        @Override
        public void onReceive(Context context, Intent intent) {
            // 外呼 对方有回应
            if (intent.getAction().equals(Constants.VOIP_CALLSTATECALL_CALLALERTING)) {
            } else if (intent.getAction().equals(Constants.VOIP_CALLSTATECALL_CALLANSWERED)) {
                if (!mIsStart) {
                }
            } else if (intent.getAction().equals(Constants.VOIP_CALLSTATECALL_CALLRELEASED)) {
            } else if (intent.getAction().equals(Constants.VOIP_CALLSTATECALL_MAKECALLFAILED)) {
            }
            
        }
        
    }
}
